from datetime import datetime
import random
import time
import json
from paho.mqtt import client as mqtt_client

# tlink/P3WX2rX1r/x3422N21N/event/propertyReport/post  tlink/w3i52s51s/t3ii2mi1m/command/setProperty/exec  tlink/X3WI1EIUE/L3QN2aN1a/command/setProperty/exec
# tlink/${productKey}/${deviceName}/command/setProperty/exec_reply
# 定义要监听的主题列表、回复的主题以及参数
from dao.mysqlhelper import MySQLHelper

# MQTT 17环境代理信息
# broker = '192.168.141.77'
# port = 1884

# MQTT 116环境代理信息
# broker = '116.205.232.249'
# port = 10015

# MQTT 202环境代理信息
from utils.config import Config

broker = '192.168.101.202'
port = 1883

# 生成客户端ID
client_id = f'testcjm|signmethod=hmacmd5|{random.randint(0, 1000)}'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print(f"Failed to connect, return code {rc}\n")

    client = mqtt_client.Client(client_id)
    client.username_pw_set("admin&admin", "bc219bd32010b7848139d1b131f71585")
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

# 记录时间戳的函数
def get_timestamp_milliseconds():
    return int(time.time() * 1000)

def sub(client: mqtt_client, topics: list, filter_string: str):
    def on_message(client, userdata, msg):
        # print(f"Received topic `{msg.topic}`:`{msg.payload.decode()}`")
        # formatted_time = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
        # print(formatted_time)
        # return formatted_time

        payload = msg.payload.decode()
        if filter_string in payload:
            # print(f"Received topic `{msg.topic}`:`{payload}`")
            mqtt_message_time = get_timestamp_milliseconds()  # 记录收到 MQTT 消息的时间戳
            formatted_time = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
            conf=Config('../conf/config.ini')
            conf.write_option_and_value('mqtt', 'mqtt_message_time', str(mqtt_message_time))
            print(f"[{mqtt_message_time}] Received MQTT message on topic '{msg.topic}': {msg.payload.decode()}")
    client.on_message = on_message


    # 循环订阅每个主题
    for topic_info in topics:
        client.subscribe(topic_info["subscribe"])

def subscribe(client: mqtt_client, topics: list):
    def on_message(client, userdata, msg):
        print(f"Received topic `{msg.topic}`:`{msg.payload.decode()}`")
        rs = json.loads(msg.payload.decode())
        reqid = rs["reqid"]
        # current_timestamp = time.time()
        # # 根据收到的消息的主题确定回复的目标主题和对应的 payload
        for topic_info in topics:
            if msg.topic == topic_info["subscribe"]:
                payload = {
                    "reqid": reqid,
                    "code": 200
                    # "data": topic_info["payload"]
                }
                # 将 payload 转换为字符串
                payload_str = json.dumps(payload)
                # 发布消息到目标主题
                client.publish(topic_info["response"], payload_str)
                print(f"Published topic `{topic_info['response']}`:{payload} ")

    # 循环订阅每个主题
    for topic_info in topics:
        client.subscribe(topic_info["subscribe"])
    client.on_message = on_message


# 把设备设置在线
def edit_sql(product_key):
    mysql = MySQLHelper()
    sql_list = ["update iot_device set device_status='online' where product_key=\'"+product_key+"'"
                ]
    sql2="select device_name from iot_device where product_key='"+product_key+"'"
    for sql in sql_list:
        mysql.dml(sql)
    res=mysql.select(sql2)
    return res

def run(product_key_list):
    topics=[]
    for product_key in product_key_list:
        topic=[]
        devs=edit_sql(product_key)   # 把设备设置在线并返回产品下的所有设备
        for dev in devs:
            map={
                "subscribe": "tlink/"+product_key+"/"+dev[0]+"/command/setProperty/exec",
                "response": "tlink/"+product_key+"/"+dev[0]+"/command/setProperty/exec_reply"
            }
            topic.append(map)
        topics+=topic
    print(topics)
    client = connect_mqtt()
    subscribe(client, topics)  # 设置监听和回复的topic
    client.loop_forever()


# if __name__ == '__main__':   # 监听产品下的所有设备topic，并回复
#     product_key_list=['W3P55i5gi','p3Lu5hugh']
#     run(product_key_list)


# if __name__ == '__main__':   # 监听某个topic，并记录时间
#     filter_string = "湘A1A81W"  #  需要过滤的数据
#     topics=[{
#         "subscribe": "bizdata/objects_list"
#     }]
#     client = connect_mqtt()
#     sub(client, topics,filter_string)  # 设置监听和回复的topic
#     client.loop_forever()
